<?php 
/**
 * @orm tablename wb_pages
 */
class WbSite extends WbPage {

	/**
	 * @orm owns many WbSiteBanner inverse parent
	 */
	public $banners;
	/**
	 * @orm array
	 * @orm listener beforeValidate beforeValidateBannerLocations
	 */
	public $bannerLocations = array();
	/**
	 * @orm owns many WbSiteDocument inverse parent
	 */
	public $documents;
	/**
	 * @orm boolean
	 * @orm listener beforeSave beforeSaveIsMainSite
	 */
	public $isMainSite;
	/**
	 * @orm char(255)
	 */
	public $title;
	
	public function getBannersHtml() {
		$banners = $this->banners->query()->where('t.active=1')->commit();
		$list = array();
		foreach( $banners as $banner ) {
			$list[$banner->location][] = $banner;
		}
		
		foreach( $list as &$spot ) {
			$spot = $spot[array_rand($spot)]->getBannerHtml();
		}
		
		return $list;
	}
	
	public function beforeSaveIsMainSite() {
		if( $this->isMainSite == true ) {
			DomSql::query('UPDATE '.WbPage::getDbTable().' SET isMainSite = 0 WHERE parent <=> NULL');
		}
	}
	
	public function getRoot() {
		return $this;
	}
	
	public function bannerLocationsToString() {
		$list = array();
		foreach( $this->bannerLocations as $location => $name ) {
			$list[] = $location.':'.$name;
		}
		return implode("\n",$list);
	}
		
	public function beforeValidateBannerLocations( &$locations ) {
		if( is_string($locations) ) {
			$new = array();
			foreach( explode("\n", $locations) as $location ) {
				$k = explode(':',$location);
				if( $k[0] != '' && $k[1] != '' ) {
					$new[$k[0]] = $k[1];
				}
			}
			$locations = $new;
		}
		return $locations;
	}

	public function getTreeIcon() {
		return 'folder';
	}
}

